package com.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.gateway.service.GatewayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * Sentinel、route
 * @Description: 网关配置限流的规则
 * @Author: mis_wu
 * @Date: 2022/4/30
 * 限流规则放入预加载中
 * 此处不用限流代码,限流在网关中配置即可
 **/
@Slf4j
@Component
public class GatewayConfigApplicationRunner implements ApplicationRunner {

    @Autowired
    private GatewayService gatewayService;

    private static final String RESOURCE_KEY = "gateway-flowRule";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        initAllGatewayRouteConfig();
//        initGatewayRules();
    }
    /**
     * 配置限流规则
     * 此处的resource不生效
     * 推荐：使用nacos动态配置
     */
    private void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule(RESOURCE_KEY)
                // 限流维度
                .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID)
                // 限流阈值
                .setCount(1)
                // 统计时间窗口，单位是秒，默认是 1 秒
                .setIntervalSec(1)
        );
        GatewayRuleManager.loadRules(rules);
        log.info(Thread.currentThread().getName()+"===...sentinel限流配置初始化成功...");
    }

    /**
     * 网关路由初始化配置
     */
    private void initAllGatewayRouteConfig(){
        gatewayService.loadAllRoutes();
        log.info(Thread.currentThread().getName()+"===...网关route配置初始化成功...");
    }
}
